package logic

import (
	"context"
	"github.com/eeppee_admin/clouddisk/service/model"
	"github.com/eeppee_admin/clouddisk/service/helper"
	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/internal/types"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserStoreSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserStoreSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserStoreSaveLogic {
	return &UserStoreSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserStoreSaveLogic) UserStoreSave(req *types.UserStoreSaveRequest, userIdentity string) (resp *types.UserStoreSaveResponse, err error) {
	// 判断文件是否超容量
	sp := new(model.StorePool)
	_, err = l.svcCtx.Engine.
		Select("size").
		Where("identity = ?", req.StoreIdentity).
		Get(sp)
	if err != nil {
		return
	}

	user := new(model.User)
	_, err = l.svcCtx.Engine.
		Select("new_volume, total_volume").
		Where("identity = ?", userIdentity).Get(user)

	if err != nil {
		return
	}

	if user.NewVolume + sp.Size > user.TotalVolume {
		err = errors.New("已经超出当前容量")
		return
	}

	// 更新当前容量
	_, err = l.svcCtx.Engine.Exec("update user set new_volume = new_volume + ? where identity = ?", sp.Size, userIdentity)
	if err != nil {
		return
	}

	// 新增关联记录
	newUserStore := &model.UserStore{
		Identity: helper.UUID(),
		UserIdentity: userIdentity,
		ParentId: req.ParentId,
		StoreIdentity: req.StoreIdentity,
		Ext: req.Ext,
		Name: req.Name,
	}

	_, err = l.svcCtx.Engine.Insert(newUserStore)
	if err != nil {
		return
	}

	return
}
